<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>添加账号</span>
      </div>
      <el-form
        :model="formData"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="账号" prop="account" class="account">
          <el-input v-model="formData.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" class="password">
          <el-input v-model="formData.password"></el-input>
        </el-form-item>
        <el-form-item label="活动区域" prop="userGroup">
          <el-select v-model="formData.userGroup" placeholder="请选择用户组">
            <el-option label="超级管理员" value="超级管理员"></el-option>
            <el-option label="普通管理员" value="普通管理员"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="commit">提交</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { addAcount, userAccountRepeat } from "@/api/user";
const checkAccount = async (rule, value, callback) => {
  if (!value) {
    callback(new Error("账号不能为空"));
  } else if (!/^[\u4E00-\u9FA5a-zA-Z0-9]{4,16}/.test(value)) {
    callback(new Error("数字、英文、中文4-16位"));
  } else {
    let res = await userAccountRepeat({
      account: value,
    });
    console.log(res);
    let {code} = res.data
    if(code===200){
      callback()
    }
  }
};
const checkPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error("密码不能为空"));
  } else if (!/^[a-zA-Z0-9]{6,12}/.test(value)) {
    callback(new Error("数字、英文6-12位"));
  } else {
    callback();
  }
};
export default {
  data() {
    return {
      formData: {
        account: "",
        password: "",
        userGroup: "",
      },
      rules: {
        account: [{ validator: checkAccount, trigger: "blur" }],
        password: [{ validator: checkPassword, trigger: "blur" }],
      },
    };
  },
  methods: {
    commit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          let res = await addAcount(this.formData);
          // console.log(res);
          let { code } = res.data;
          if (code === 0) {
            this.$router.push("/account");
          }
        }
      });
    },
    reset() {
      this.$refs.formRef.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.box-card {
  width: 600px;
  margin-top: 20px;
  margin-left: 20px;
}
.account {
  width: 350px;
}
.password {
  width: 350px;
}
.el-button--primary {
  background-color: #d99bac;
  border: 0;
}
</style>